package com.powerwyx.shortlink.project.mq.idempotent;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.powerwyx.shortlink.project.common.constant.RedisConstant.RABBIT_MQ_MESSAGE_ID;

/**
 * 消息幂等组件
 * @author 王艺锡
 * @version 1.0
 */
@Component
@Slf4j
public class MessageQueueIdempotent {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 判断消息是否已经消费
     * @param messageId 消息唯一标识
     * @return
     */
    public boolean isConsumed(String messageId){
        String key = RABBIT_MQ_MESSAGE_ID + messageId;
        //0表示幂等标识已经设置成，但是业务流程还未完成
        return Boolean.TRUE.equals(stringRedisTemplate.opsForValue().setIfAbsent(key,"0",2L, TimeUnit.MINUTES));
    }

    /**
     * 判断业务流程是否成功执行
     * @param messageId 消息唯一标识
     * @return
     */
    public boolean isAccomplish(String messageId){
        String key = RABBIT_MQ_MESSAGE_ID + messageId;
        //1表示幂等标识已经设置成，并且业务流程已经完成
        return Objects.equals(stringRedisTemplate.opsForValue().get(key),"1");
    }


    /**
     * 如果业务异常，删除幂等标识
     * @param messageId
     * @return
     */
    public void delIdempotent(String messageId){
        String key = RABBIT_MQ_MESSAGE_ID + messageId;
        stringRedisTemplate.delete(key);
    }

    /**
     * 业务执行成功，设置幂等标识为已完成
     * @param messageId
     */
    public void setAccomplish(String messageId){
        String key = RABBIT_MQ_MESSAGE_ID + messageId;
        stringRedisTemplate.opsForValue().set(key,"1",2L, TimeUnit.MINUTES);
    }

}
